/**
 * earth-now.co
 * Author:  Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * File:    apps/web/app/embed/[id]/page.tsx
 * Purpose: Minimal standalone embed page — one fullscreen LiveCounter for iframes (?window=&lang=), no chrome, earth-now.co attribution
 */

import EmbedCounter from "@/components/EmbedCounter";
import { fetchMetrics, fetchModels } from "@/lib/api";
import { resolveModel, resolvePrimaryWindow } from "@/lib/derived";
import { DEFAULT_LOCALE, isLocale } from "@/lib/messages";
import type { CounterWindow } from "@earth-now/counter";

export const dynamic = "force-dynamic";

function isWindow(value: unknown): value is CounterWindow {
  return value === "today" || value === "ytd" || value === "session" || value === "total";
}

export default async function EmbedPage({
  params,
  searchParams,
}: {
  params: { id: string };
  searchParams?: { window?: string; lang?: string };
}) {
  const langParam = searchParams?.lang;
  const locale = isLocale(langParam) ? langParam : DEFAULT_LOCALE;

  try {
    const [metrics, modelsResponse] = await Promise.all([fetchMetrics(), fetchModels()]);
    const metric = metrics.find((m) => m.id === params.id);
    if (metric === undefined) {
      return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-page text-sm text-ink2">
          {locale === "fr" ? "Métrique introuvable" : "Metric not found"} — earth-now.co
        </div>
      );
    }
    const windowParam = searchParams?.window;
    const counterWindow = isWindow(windowParam) ? windowParam : resolvePrimaryWindow(metric);
    return (
      <EmbedCounter
        metric={metric}
        model={resolveModel(metric, modelsResponse.models)}
        window={counterWindow}
        locale={locale}
      />
    );
  } catch {
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center bg-page text-sm text-ink2">
        API offline — earth-now.co
      </div>
    );
  }
}
